<?php
/**
 * @Author:      lyt
 * @DateTime:    2016-01-13 09:41:56
 * @Description: 对于车辆 基础信息的查询
 */
class ScsCarController extends BaseController {
    /*
     * 保存车辆信息
     * */
    public function store(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'car_no' => 'required',
                'mile' => 'required',
                'vin' => 'required',
//                'brand' => 'required',
//                'series' => 'required',
                'model' => 'required',
//                'year' => 'required',
//                'city' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");
            $mile = Input::get("mile");
            $car_no = Input::get("car_no");
            $vin = Input::get("vin");
            $brand = Input::get("brand");
            $series = Input::get("series");
            $model = Input::get("model");
            $year = Input::get("year");
            $city = Input::get("city");//服务城市


            $insurance = Input::get("insurance");//保险过期日
            $filiale = Input::get("filiale");//分公司
            $department = Input::get("department");//部门
            
            $bookin_date = Input::get("bookin_date");//初登日期
            $dept_name = Input::get("dept_name");//单位
            $on_type = Input::get("on_type");//班别
            $card_no = Input::get("card_no");//档案编号
            $name = Input::get("name");//姓名
            $phone = Input::get("phone");//手机号

            $user_car_id = Input::get("user_car_id");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            try {
                if($user_car_id != ''){
                    $user_car_info = UserCarInfo::where('id',$user_car_id)->first();
                    if($mile != '') $user_car_info->mileage = $mile;
                    if($vin != '') $user_car_info->vin_code = $vin;
                    if($car_no != '') $user_car_info->car_no = $car_no;
                    if($brand != '') $user_car_info->car_brand_id = $brand;
                    if($series != '') $user_car_info->car_series_id = $series;
                    if($model != '') $user_car_info->car_model_id = $model;
                    if($insurance != '') $user_car_info->insurance = $insurance;
                    if($filiale != '') $user_car_info->filiale = $filiale;
                    if($department != '') $user_car_info->department = $department;
                    $user_car_info->save();

                    $user_type = Users::where('id',$user_id)->where('status',1)->select('type')->first();
                    if($user_type->type == 2){
                        $user_car_desc = UserCarDesc::where('id',$user_car_id)->first();
                        $user_car_desc->bookin_date = is_null($bookin_date)||$bookin_date==''?null:$bookin_date;
                        if($dept_name != '') $user_car_desc->dept_name = $dept_name;
                        if($on_type != '') $user_car_desc->on_type = $on_type;
                        if($card_no != '') $user_car_desc->card_no = $card_no;
                        if($name != '') $user_car_desc->name = $name;
                        if($phone != '') $user_car_desc->phone = $phone;
                        $user_car_desc->save();
                    }
                }else{
                    $count = UserCarInfo::where('car_no',$car_no)->where('user_id',$user_id)->where('status',1)->count();
                    if($count > 0){
                        $response = array('code' => -1, 'msg' => '企业已有该车辆', 'result' => array());
                        break;
                    }else{
                        $user_car_info = new UserCarInfo();
                        $user_car_info->user_id = $user_id;
                        $user_car_info->mileage = $mile;
                        $user_car_info->vin_code = $vin;
                        $user_car_info->car_no = $car_no;
                        $user_car_info->car_brand_id = $brand;
                        $user_car_info->car_series_id = $series;
                        $user_car_info->car_model_id = $model;
                        $user_car_info->insurance = $insurance;
                        $user_car_info->filiale = $filiale;
                        $user_car_info->department = $department;
                        $user_car_info->status = 1;
                        $user_car_info->save();

                        $user_type = Users::where('id',$user_id)->where('status',1)->select('type')->first();
                        if($user_type->type == 2){
                            $user_car_desc = new UserCarDesc();
                            $user_car_desc->id = $user_car_info->id;
                            $user_car_desc->bookin_date = is_null($bookin_date)||$bookin_date==''?null:$bookin_date;
                            $user_car_desc->dept_name = $dept_name;
                            $user_car_desc->on_type = $on_type;
                            $user_car_desc->card_no = $card_no;
                            $user_car_desc->name = $name;
                            $user_car_desc->phone = $phone;
                            $user_car_desc->save();
                        }
                    }

                    $result = array('id'=> $user_car_info->id );
                    $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
                    }
            }catch(Exception $e){
                $response = array('code' => -1, 'msg' => '保存失败');
                break;
            }
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "car", "event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 车辆列表
     * */
    public function detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_id' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $car_id = Input::get("car_id");
            $user_id = Input::get("user_id");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $cars = UserCarInfo::leftJoIn("anhui_data.car_standard_info","user_car_info.car_model_id","=","anhui_data.car_standard_info.id")
                ->leftJoIn('user_car_desc','user_car_desc.id','=','user_car_info.id')
                ->select("user_car_info.*",'user_car_desc.*','car_standard_info.brand_name','car_standard_info.series_name','car_standard_info.model_name')
                ->where('user_id',$user_id)
                ->where('user_car_info.id',$car_id)
                ->get()
                ->toArray();

            $count = UserCarInfo::where('user_id',$user_id)
                ->count();

            $result = array(
                'count' => $count,
                'cars' => $cars
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        // Log::info("info", array("system" => "scs" ,"model" => "car", "event" => "detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /*
     * 车辆列表
     * */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 0);

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $cars = UserCarInfo::leftJoIn("anhui_data.car_standard_info","user_car_info.car_model_id","=","anhui_data.car_standard_info.id")
                ->select("user_car_info.*",'car_standard_info.brand_name','car_standard_info.series_name','car_standard_info.model_name')
                ->where('user_id',$user_id)
                ->skip($page_size*($page-1))
                ->take($page_size)
                ->get()
                ->toArray();

            $count = UserCarInfo::where('user_id',$user_id)
                ->count();

            $result = array(
                'count' => $count,
                'cars' => $cars
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "car", "event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-13 09:42:21
     * @Description: 获取车辆型号 根据车品牌 车系和年款 获取车型
     */
    public function models(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'brand' => 'required',
                'series' => 'required',
                'year' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            //传入参数
            // $token = Input::get('token');
            $brand = Input::get('brand');
            $series = Input::get('series');
            $year = urldecode(Input::get('year'));

            //验证token
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){                
                break;
            }

            //获取品牌车辆的厂商
            $models = DataCarStandardInfo::where('brand_name_id',$brand)
                ->where('series_name_id',$series)
                ->where('model_year',$year)
                ->where('status',1)
                ->select(array('id','model_name as model','oil_viscosity'))
                ->distinct()
                ->get()->toArray();
            foreach ($models as $_m) {
                // $temp_oil=DataCarMaintenanceClassificationConfig::where("model_id",$_m['id'])->where("status",1)->where("subject_id",1)->first();
                $_m["oil_viscosity"]='';
            }

            $count = count($models);
            $result = array(
                'count' => $count,
                'models' => $models
            );

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        // Log::info("info", array("system" => "sce" ,"event" => "models", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-01-13 09:50:14
     * @Description: 获取 指定车品牌车系 的车型年款
     */
    public function years(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'brand' => 'required',
                'series' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //传入参数
            // $token = Input::get('token');
            $brand = Input::get('brand');
            $series = Input::get('series');

            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){                
                break;
            }

            //获取品牌车辆的厂商
            $years = DataCarStandardInfo::where('brand_name_id',$brand)
                ->where('series_name_id',$series)->where('status', 1)
                ->select(array('model_year as year'))
                ->distinct()
                ->get()->toArray();
            $count = count($years);
            $result = array(
                'count' => $count,
                'years' => $years
            );

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        // Log::info("info", array("system" => "sce" ,"event" => "years", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-01-13 09:53:13
     * @Description: 获取指定品牌的车系
     */
    public function series(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'brand' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //传入参数
            // $token = Input::get('token');
            $brand = Input::get('brand');

            //验证token
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){                
                break;
            }

            //获取品牌车辆的厂商
            $factories = DataCarStandardInfo::where('brand_name_id',$brand)               
                ->select(array('series_shop_id','series_shop'))->where('status', 1)
                ->distinct()
                ->get();
            $car_factories = array();
            if(!is_null($factories)){
                foreach ($factories as $_factory) {
                    $series = DataCarStandardInfo::where('brand_name_id',$brand)
                        ->where('series_shop_id',$_factory->series_shop_id)->where('status', 1)
                        ->select(array('series_name_id as id','series_name as name'))
                        ->distinct()
                        ->get()->toArray();
                    $factory = array(
                        'factory' => $_factory->series_shop,
                        'count' => count($series),
                        'series' => $series
                    );
                    array_push($car_factories,$factory);
                }
            }
            $result = array(
                'count' => count($car_factories),
                'factories' => $car_factories
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        // Log::info("info", array("system" => "sce" ,"event" => "series", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-01-13 10:06:45
     * @Description: 获取的车型
     */
    public function brands(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //传入参数
            // $token = Input::get('token');

            //验证token
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){                
                break;
            }

            //获取车辆品牌信息
            $brands = DataCarBrand::select(array('id','initial','name','icon'))->where('status', 1)
                ->get()->toArray();
            $count = count($brands);
            $result = array(
                'count' => $count,
                // 'base_icon_url' => Config::get('car.base_icon_url'),
                'brands' => $brands
            );

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        // Log::info("info", array("system" => "sce" ,"event" => "brands", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-01-15 11:35:41
     * @Description: 用于指定车型的 保养手册
     */
    public function carMainManual(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_model_id' => 'required',
                'mileage' => 'required|Integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            //验证token
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){                
                break;
            }
            $csi=DataCarStandardInfo::find(Input::get("car_model_id"));
            if(is_null($csi)){//说明是车辆状态异常
                $response = Lang::get("scs_error.car_model_is_empty23000");
                break;
            }
            // $temp_cm=CarMaintenance::where("model_id",$csi->id)->where("status",1)->where("kilometers","<",Input::get("mileage"))->orderBy("kilometers","desc")->first();
            $temp_cm=DataCarMaintenance::where("car_model_id",$csi->id)->where("status",1)->where("kilometers","<",Input::get("mileage"))->orderBy("kilometers","desc")->first();
            $_start_km=isset($temp_cm->kilometers)?$temp_cm->kilometers:0;//找出小于 指定里程 的最大里程 为起点

            $sybject_maintenance = array();
            $car_maintenance = DataCarMaintenance::leftjoin('anhui_data.car_maintenance_classification','car_maintenance.id','=','car_maintenance_classification.car_maintenace_id')
            ->leftjoin('supply_classification','supply_classification.id','=','car_maintenance_classification.supply_classification_id')
            ->where('car_maintenance.car_model_id',$csi->id)
            ->where('car_maintenance.status',1)
            ->where('supply_classification.status',1)
            ->where('car_maintenance.kilometers',">=",$_start_km)
            ->select('car_maintenance.kilometers','supply_classification.name','supply_classification.id')
            ->orderBy('car_maintenance.kilometers','asc')
            ->orderBy('supply_classification.id','asc')
            ->get()->toArray();
            if(is_null($car_maintenance) || count($car_maintenance) <= 0 ){  //如果用默认的保养手册              
                $default_maintenance = DataCarMaintenance::$default_maintenance;
                $subjct_array=array();
                $temp_subjct_array=SupplyClassification::where("status",1)->get()->toArray();//构造一个 品类id为键 的数组
                foreach ($temp_subjct_array as $_arr) {
                    $subjct_array[$_arr["id"]]=array("id"=>$_arr["id"],"name"=>$_arr["name"]);
                }
                foreach($default_maintenance as $k => $d_m){
                    if($k<Input::get("mileage")){
                        continue;
                    }
                    $temp_arr=array();
                    $explode_arr = array_unique(explode(",", rtrim($d_m, ','))); //切割去重
                    foreach($explode_arr as $v){
                        $default_maintenance_temp = array();
                        $temp_arr[] = $subjct_array[$v];
                    }
                    $sybject_maintenance[$k]=$temp_arr;
                }
            }else{
                foreach ($car_maintenance as $_cm) {
                    if(isset($sybject_maintenance[$_cm['kilometers']])){
                        $sybject_maintenance[$_cm['kilometers']][]=array("id"=>$_cm["id"],"name"=>$_cm["name"]);
                    }else{
                        $sybject_maintenance[$_cm['kilometers']]=array(array("id"=>$_cm["id"],"name"=>$_cm["name"]));
                    }
                }
            }
            $fianle_arr=array();
            foreach ($sybject_maintenance as $key => $value) {
                $fianle_arr[]=array("kilometers"=>$key,"item"=>$value);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>count($fianle_arr),"mainManual"=>$fianle_arr));
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "brands", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-2-28 11:50:45
     * @Description: 根据车型id获取车型信息
     */
    public function car_model_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_model_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            //传入参数
            $car_model_id = Input::get('car_model_id');
    
            //验证token
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
    
            //获取品牌车辆的厂商
            $car_model_info = DataCarStandardInfo::where('id',$car_model_id)->select('id','brand_name_id','series_name_id','model_year')->first();
            $result = array(
                'car_model_info' => $car_model_info,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "models", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}